<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/reset.css">
    <style>
        .title {
            line-height: 40px;
        }

        .list {
            margin-top: 20px;
        }

        .list li {
            height: 32px;
            line-height: 32px;
            border: 1px dashed #333;
        }
    </style>
</head>

<body>
    <div id="wrap">
        <button class="add">新增</button>
        <button class="del">删除</button>
        <ul class="list one">
            <li>01</li>
            <li>02</li>
            <li>03</li>
            <li>04</li>
            <li>05</li>
            <li>06</li>
        </ul>
    </div>
</body>
<script>

    // 传统的多元素绑定事件的缺点:
    // 1. 遍历伪数组,给每个元素绑定了事件(lix6 => 事件x6 => 之间执行的内容都是一样的) => 占内存
    // 2. 无法给未来生成的元素绑定事件(页面加载时没有,后续又生成的元素) 

    // 页面加载时 给获取到的li绑定事件
    var list = document.getElementsByClassName("list")[0];
    var liList = list.getElementsByTagName("li");

    var add = document.querySelector(".add");
    var del = document.querySelector(".del");

    // lix6 => function(){} x 6
    for (let i = 0; i < liList.length; i++) {
        let li = liList[i];
        li.onclick = function () {
            console.log(this, i);
        }
    }



    add.onclick = function () {
        // 创建元素节点
        var li = document.createElement("li");
        li.innerText = "我是新增的li";
        li.setAttribute("class", "newLi");
        li.style.backgroundColor = "red";
        list.append(li);

        console.log("liList", liList);
    }

    del.onclick = function () {
        var last = list.lastElementChild;
        last.remove();

        console.log("liList", liList);
    }



</script>

</html>